package com.letv.core.utils;

import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import com.letv.android.sdk.R;
import com.letv.component.player.LetvVideoViewBuilder.Type;
import com.letv.component.player.core.LetvMediaPlayerManager;
import com.letv.component.player.core.PlayUrl;
import com.letv.component.player.utils.NativeInfos;
import com.letv.core.bean.DDUrlsResultBean;
import com.letv.core.bean.VideoFileBean;
import com.letv.core.bean.VideoFileBean.VideoSchedulingAddress;
import com.letv.core.config.LetvConfig;
import com.letv.core.constant.LetvConstant.DialogMsgConstantId;
import com.letv.core.db.PreferencesManager;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.LetvBase64;

/**
 * 视频相关工具类
 *
 * @author zhuqiao
 */
public class PlayUtils {

    public final static String BRLIST_350 = "mp4_350"; // 流畅
    public final static String BRLIST_1000 = "mp4_1000"; // 标清
    public final static String BRLIST_1300 = "mp4_1300"; // 高清
    public final static String BRLIST_FLV_800 = "flv_800";
    public final static String BRLIST_FLV_1300 = "flv_1300";
    public final static String BRLIST_FLV_720p = "flv_720p";
    public final static String BRLIST_FLV_1080p = "flv_1080p";

    /**
     * 码流类型
     */
    public interface PLAY_LEVEL {

        /**
         * 极速
         */
        int LOW = 1;

        /**
         * 流畅
         */
        int STANDARD = 2;

        /**
         * 高清
         */
        int HIGH = 3;

        /**
         * 超清
         */
        int SUPERHIGH = 4;
    }

    public interface StreamTypePlayerLibs {

        int STREAM_TYPE_800 = 0;

        int STREAM_TYPE_1300 = 1;

        int STREAM_TYPE_720p = 2;

        int STREAM_TYPE_1080p = 3;
    }

    /**
     * 获取调度地址
     *
     * @param videoFile
     * @param playLevel
     *         是否高清
     * @return
     */
    public static DDUrlsResultBean getDDUrls(VideoFileBean videoFile, int playLevel,
                                             int supportLevel) {
        String streamLevel = "13";
        String[] urls = new String[4];
        VideoSchedulingAddress address = null;
        int realPlayLevel = playLevel;
        boolean hasSuperHigh = false;
        boolean hasHigh = false;
        boolean hasStandard = false;
        boolean hasTopSpeed = false;// 是否有极速码流档

        if (videoFile.getMp4_1300() != null && supportLevel >= NativeInfos.SUPPORT_TS1300K_LEVEL) {
            hasSuperHigh = true;
        }
        if (videoFile.getMp4_1000() != null && supportLevel >= NativeInfos.SUPPORT_TS1000K_LEVEL) {
            hasHigh = true;
        }
        if (videoFile.getMp4_180() != null && supportLevel >= NativeInfos.SUPPORT_MP4_LEVEL) {
            hasTopSpeed = true;
        }
        if (videoFile.getMp4_350() != null) {
            hasStandard = true;
        }
        LogInfo.log("sguotao",
                "playLevel =" + playLevel + " hasSuperHigh=" + hasSuperHigh + " hasHigh =" +
                        hasHigh + " hasStandard =" + hasStandard + " hasTopSpeed =" + hasTopSpeed);
        DDUrlsResultBean result = new DDUrlsResultBean();
        // LogInfo.log("ddurl",
        // "getMp4_1000 ="+videoFile.getMp4_1000()+" getMp4_350 = "+videoFile.getMp4_350()+" getMp4_180 ="+videoFile.getMp4_180());
        switch (playLevel) {
            case PLAY_LEVEL.SUPERHIGH:
                if (hasSuperHigh) {
                    address = videoFile.getMp4_1300();
                    streamLevel = "13";
                    result.streamType = "Mp4_1300";

                } else if (hasHigh) {
                    address = videoFile.getMp4_1000();
                    realPlayLevel = PLAY_LEVEL.HIGH;
                    streamLevel = "13";
                    result.streamType = "Mp4_1000";
                } else if (hasTopSpeed) {
                    address = videoFile.getMp4_180();
                    streamLevel = "21";
                    realPlayLevel = PLAY_LEVEL.LOW;
                    result.streamType = "Mp4_180";
                } else {
                    address = videoFile.getMp4_350();
                    streamLevel = "21";
                    realPlayLevel = PLAY_LEVEL.STANDARD;
                    result.streamType = "Mp4_350";
                }
                break;
            case PLAY_LEVEL.HIGH:
                if (hasHigh) {
                    address = videoFile.getMp4_1000();
                    streamLevel = "13";
                    result.streamType = "Mp4_1000";
                } else if (hasTopSpeed) {
                    address = videoFile.getMp4_180();
                    streamLevel = "21";
                    realPlayLevel = PLAY_LEVEL.LOW;
                    result.streamType = "Mp4_180";
                } else {
                    address = videoFile.getMp4_350();
                    streamLevel = "21";
                    realPlayLevel = PLAY_LEVEL.STANDARD;
                    result.streamType = "Mp4_350";
                }
                break;
            case PLAY_LEVEL.STANDARD:
                if (hasStandard) {
                    address = videoFile.getMp4_350();
                    streamLevel = "21";
                    result.streamType = "Mp4_350";
                } else if (hasTopSpeed) {
                    address = videoFile.getMp4_180();
                    streamLevel = "21";
                    realPlayLevel = PLAY_LEVEL.LOW;
                    result.streamType = "Mp4_180";
                } else {
                    address = videoFile.getMp4_1000();
                    streamLevel = "13";
                    realPlayLevel = PLAY_LEVEL.HIGH;
                    result.streamType = "Mp4_1000";
                }
                break;

            case PLAY_LEVEL.LOW:
                if (hasTopSpeed) {
                    address = videoFile.getMp4_180();
                    streamLevel = "21";
                    result.streamType = "Mp4_180";
                } else if (hasStandard) {
                    address = videoFile.getMp4_350();
                    streamLevel = "21";
                    realPlayLevel = PLAY_LEVEL.STANDARD;
                    result.streamType = "Mp4_350";
                } else {
                    address = videoFile.getMp4_1000();
                    streamLevel = "13";
                    realPlayLevel = PLAY_LEVEL.HIGH;
                    result.streamType = "Mp4_1000";
                }
                break;
        }
        String stream;
        for (int level = PLAY_LEVEL.LOW; level <= PLAY_LEVEL.SUPERHIGH; level++) {
            switch (level) {
                case PLAY_LEVEL.SUPERHIGH:
                    if (hasSuperHigh) {
                        stream = "Mp4_1300";

                    } else if (hasHigh) {
                        stream = "Mp4_1000";
                    } else if (hasTopSpeed) {
                        stream = "Mp4_180";
                    } else {
                        stream = "Mp4_350";
                    }
                    videoFile.streamLevelMaps.put(PLAY_LEVEL.SUPERHIGH, stream);
                    break;
                case PLAY_LEVEL.HIGH:
                    if (hasHigh) {
                        stream = "Mp4_1000";
                    } else if (hasTopSpeed) {
                        stream = "Mp4_180";
                    } else {
                        stream = "Mp4_350";
                    }
                    videoFile.streamLevelMaps.put(PLAY_LEVEL.HIGH, stream);
                    break;
                case PLAY_LEVEL.STANDARD:
                    if (hasStandard) {
                        stream = "Mp4_350";
                    } else if (hasTopSpeed) {
                        stream = "Mp4_180";
                    } else {
                        stream = "Mp4_1000";
                    }
                    videoFile.streamLevelMaps.put(PLAY_LEVEL.STANDARD, stream);
                    break;

                case PLAY_LEVEL.LOW:
                    if (hasTopSpeed) {
                        stream = "Mp4_180";
                    } else if (hasStandard) {
                        stream = "Mp4_350";
                    } else {
                        stream = "Mp4_1000";
                    }
                    videoFile.streamLevelMaps.put(PLAY_LEVEL.LOW, stream);
                    break;
            }
        }

        if (address != null) {
            urls[0] = address.getMainUrl();
            urls[1] = address.getBackUrl0();
            urls[2] = address.getBackUrl1();
            urls[3] = address.getBackUrl2();
            result.setStorepath(address.getStorepath());
        }

        result.setHasHigh(hasHigh);
        result.setHasStandard(hasStandard);
        result.setHasLow(hasTopSpeed);
        result.setHasSuperHigh(hasSuperHigh);
        result.setPlayLevel(realPlayLevel);
        result.setDolby(false);
        result.setDdurls(urls);
        result.setStreamLevel(streamLevel);
        return result;
    }

    /**
     * 获取调度地址
     *
     * @param videoFile
     *         是否高清
     * @return
     */
    public static DDUrlsResultBean getDDUrls(VideoFileBean videoFile, int playLevel,
                                             boolean isDolbyChannel, int supportLevel) {
        String streamLevel = "13";
        String[] urls = new String[4];
        VideoSchedulingAddress address = null;
        if (isDolbyChannel) {
            int realPlayLevel = PLAY_LEVEL.HIGH;
            address = videoFile.getMp4_800_db();
            if (null == address) {
                address = videoFile.getMp4_1300_db();
                realPlayLevel = PLAY_LEVEL.SUPERHIGH;
                streamLevel = "24";
            }
            if (null == address) {
                address = videoFile.getMp4_720p_db();
                realPlayLevel = PLAY_LEVEL.STANDARD;
                streamLevel = "25";
            }
            if (null == address) {
                address = videoFile.getMp4_1080p6m_db();
                realPlayLevel = PLAY_LEVEL.SUPERHIGH;
                streamLevel = "26";
            }
            if (null != address) {
                urls[0] = address.getMainUrl();
                urls[1] = address.getBackUrl0();
                urls[2] = address.getBackUrl1();
                urls[3] = address.getBackUrl2();

                DDUrlsResultBean result = new DDUrlsResultBean();
                result.setHasHigh(true);
                result.setHasStandard(false);
                result.setHasLow(false);
                result.setDolby(true);
                result.setPlayLevel(realPlayLevel);
                result.setDdurls(urls);
                result.setStorepath(address.getStorepath());
                result.setStreamLevel(streamLevel);
                return result;
            } else {
                return getDDUrls(videoFile, playLevel, supportLevel);
            }
        } else {
            return getDDUrls(videoFile, playLevel, supportLevel);
        }
    }

    /**
     * 拼接g3播放地址
     *
     * @param urls
     * @return
     */
    //    public static String getDdUrl(String[] urls, String token, String uid, String vid) {
    //        return getDdUrl(urls, token, uid, vid, false);
    //    }
    public static String getDdUrl(Context context, String[] urls, String token, String uid,
                                  String vid) {
        return getDdUrl(context, urls, token, uid, vid, false);
    }

    //    public static String getDdUrl(String[] urls, String token, String uid, String vid, boolean isWoUser) {
    //        if (BaseTypeUtils.isArrayEmpty(urls)) {
    //            return null;
    //        }
    //
    //        for (int i = 0; i < urls.length; i++) {
    //            if (TextUtils.isEmpty(urls[i])) {
    //                continue;
    //            }
    //            String baseUrl = urls[i];
    //            baseUrl += "&pcode=" + LetvConfig.getPcode();
    //            baseUrl += "&version=" + LetvUtils.getClientVersionName();
    //            if (PreferencesManager.getInstance().isLogin()) {// 登录加速
    //                baseUrl += "&iscpn=f9050";
    //                if (!isWoUser) {
    //                    baseUrl += "&uinfo=" + PreferencesManager.getInstance().getUInfo();
    //                }
    //            }
    //            if (!TextUtils.isEmpty(token)) {
    //                baseUrl += "&token=" + token;
    //            }
    //            if (!TextUtils.isEmpty(uid)) {
    //                baseUrl += "&uid=" + uid;
    //            }
    //            if (isWoUser) {
    //                baseUrl += "&freecnc=1";
    //            }
    //            baseUrl += "&p1=0&p2=00&uuid=" + LetvUtils.getUUID(BaseApplication.getInstance());
    //            baseUrl += "&vid=" + vid;
    //
    //            return replaceM3v(baseUrl);
    //        }
    //        return null;
    //    }

    public static String getDdUrl(Context context, String[] urls, String token, String uid,
                                  String vid, boolean isWoUser) {
        if (BaseTypeUtils.isArrayEmpty(urls)) {
            return null;
        }

        for (int i = 0; i < urls.length; i++) {
            if (TextUtils.isEmpty(urls[i])) {
                continue;
            }
            String baseUrl = urls[i];
            baseUrl += "&pcode=" + LetvConfig.getPcode(context);
            baseUrl += "&version=" + LetvUtils.getClientVersionName(context);
            if (PreferencesManager.getInstance(context).isLogin()) {// 登录加速
                baseUrl += "&iscpn=f9050";
                if (!isWoUser) {
                    baseUrl += "&uinfo=" + PreferencesManager.getInstance(context).getUInfo();
                }
            }
            if (!TextUtils.isEmpty(token)) {
                baseUrl += "&token=" + token;
            }
            if (!TextUtils.isEmpty(uid)) {
                baseUrl += "&uid=" + uid;
            }
            if (isWoUser) {
                baseUrl += "&freecnc=1";
            }
            //            baseUrl += "&p1=0&p2=00&uuid=" + LetvUtils.getUUID(context);
            baseUrl += "&p1=" + DataStatistics.readProperties("letv.p1") + "&p2=" +
                    DataStatistics.readProperties("letv.p2") + "&uuid=" +
                    LetvUtils.getUUID(context);
            baseUrl += "&vid=" + vid;

            return replaceM3v(baseUrl);
        }
        return null;
    }

    /**
     * 替换m3v
     * </br>
     * 1:20s;3:12s;4:10
     *
     * @param url
     * @return
     */
    private static String replaceM3v(String url) {
        if (!url.contains("&m3v=")) {
            return url;
        }

        String replace = "&m3v=" + PreferencesManager.getInstance().getM3v();
        for (int i = 0; i < 10; i++) {
            String old = "&m3v=" + i;
            if (url.contains(old)) {
                return url.replace(old, replace);
            }
        }

        return url;
    }

    /**
     * 获取真正播放地址
     *
     * @param urls
     * @return
     */
    //    public static String getRealUrl(String[] urls, String token, String uid, String vid) {
    //        if (BaseTypeUtils.isArrayEmpty(urls)) {
    //            return null;
    //        }
    //
    //        try {
    //            String baseUrl = getDdUrl(urls, token, uid, vid);
    //            if (BaseApplication.getInstance().getCdeHelper() != null) {
    //                String linkShellUrl = BaseApplication.getInstance().getCdeHelper().getLinkshellUrl(baseUrl);
    //                if (!TextUtils.isEmpty(linkShellUrl)) {
    //                    baseUrl = linkShellUrl;
    //                }
    //            }
    //            return baseUrl;
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }
    //
    //        return null;
    //    }
    public static String getRealUrl(Context context, String[] urls, String token, String uid,
                                    String vid) {
        if (BaseTypeUtils.isArrayEmpty(urls)) {
            return null;
        }

        try {
            String baseUrl = getDdUrl(context, urls, token, uid, vid);
            if (LetvSDKUtils.getCdeHelper(context) != null) {
                String linkShellUrl = LetvSDKUtils.getCdeHelper(context).getLinkshellUrl(baseUrl);
                if (!TextUtils.isEmpty(linkShellUrl)) {
                    baseUrl = linkShellUrl;
                }
            }
            return baseUrl;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    // /**
    // * 获取真正播放地址
    // *
    // * @param baseUrl
    // * @return
    // */
    // public static String getRealUrlForWo(String baseUrl, String token, String uid) {
    // RealPlayUrlInfo mRealPlayUrlInfo = null;
    //
    // if (baseUrl == null) {
    // return null;
    // }
    //
    // try {
    // mRealPlayUrlInfo = new RealPlayUrlInfo();
    // mRealPlayUrlInfo.setDdUrl(baseUrl);
    // return baseUrl;
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    //
    // return null;
    // }

    /**
     * 是否支持高清
     *
     * @param brList
     * @return
     */
    public static boolean isSupportHD(String brList) {
        if (TextUtils.isEmpty(brList)) {
            return false;
        }

        return brList.contains(BRLIST_1300) && H265Utils.isSupport1300() &&
                !"lenovo k910".equalsIgnoreCase(Build.MODEL);

    }

    /**
     * 是否支持标清
     *
     * @param brList
     * @return boolean
     */
    public static boolean isSupportStandard(String brList) {
        if (TextUtils.isEmpty(brList)) {
            return false;
        }

        return brList.contains(BRLIST_1000);

    }

    /**
     * 是否支持流畅
     *
     * @param brList
     * @return boolean
     */
    public static boolean isSupportLow(String brList) {
        if (TextUtils.isEmpty(brList)) {
            return false;
        }

        return brList.contains(BRLIST_350);

    }

    /**
     * 是否支持flv800
     *
     * @param brList
     * @return boolean
     */
    public static boolean isSupportFlv800(String brList) {
        if (TextUtils.isEmpty(brList)) {
            return false;
        }

        return brList.contains(BRLIST_FLV_800);

    }

    /**
     * 是否支持flv1300
     *
     * @param brList
     * @return boolean
     */
    public static boolean isSupportFlv1300(String brList) {
        if (TextUtils.isEmpty(brList)) {
            return false;
        }

        return brList.contains(BRLIST_FLV_1300);

    }

    /**
     * 是否支持flv1720p
     *
     * @param brList
     * @return boolean
     */
    public static boolean isSupportFlv720p(String brList) {
        if (TextUtils.isEmpty(brList)) {
            return false;
        }

        return brList.contains(BRLIST_FLV_720p);

    }

    /**
     * 是否支持flv11080p
     *
     * @param brList
     * @return boolean
     */
    public static boolean isSupportFlv1080p(String brList) {
        if (TextUtils.isEmpty(brList)) {
            return false;
        }

        return brList.contains(BRLIST_FLV_1080p);

    }

    /**
     * 暂时默认为TS流
     */
    public static String getTss() {
        return "ios";
    }

    /**
     * 广告拼接播放串（TS流才支持）
     */
    public static String splitJointPlayUrl(String playUrl, String adUrl) {
        try {
            String host = Uri.parse(playUrl).getHost();
            String baseUrl = "http://" + host + "/gate_way.m3u8?ID=id9,id10&id9.proxy_url=";
            adUrl = LetvBase64.encode(adUrl.getBytes("UTF-8"));
            playUrl = LetvBase64.encode(playUrl.getBytes("UTF-8"));
            StringBuffer sb = new StringBuffer();
            sb.append(baseUrl);
            sb.append(adUrl);
            sb.append("&id10.proxy_url=");
            sb.append(playUrl);
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getCode(int playLevel) {
        String code = "";
        switch (playLevel) {
            case PLAY_LEVEL.LOW:
                code = "160";
                break;
            case PLAY_LEVEL.STANDARD:
                code = "350";
                break;
            case PLAY_LEVEL.HIGH:
                code = "800";
                break;
        }
        return code;
    }

    public static String getStreamLevel(int type) {
        String streamLevel = "47";
        switch (type) {
            case StreamTypePlayerLibs.STREAM_TYPE_800:
                streamLevel = "47"; // H265_flv_800类型值为47
                break;
            case StreamTypePlayerLibs.STREAM_TYPE_1300:
                streamLevel = "48"; // H265_flv_1300类型值为48
                break;
            case StreamTypePlayerLibs.STREAM_TYPE_720p:
                streamLevel = "49"; // H265_flv_720p类型值为49
                break;
            case StreamTypePlayerLibs.STREAM_TYPE_1080p:
                streamLevel = "50"; // H265_flv_1080p类型值为50
                break;
        }
        return streamLevel;
    }

    /**
     * 获取最大支持码流
     *
     * @return
     */
    public static int getMaxStreamLevel() {
        if (LetvMediaPlayerManager.getInstance().getHardDecodeSupportLevel() == 5) {
            return 4;
        }

        if (LetvMediaPlayerManager.getInstance().getHardDecodeSupportLevel() == 4) {
            return 3;
        }

        if (LetvMediaPlayerManager.getInstance().getHardDecodeSupportLevel() == 2) {
            return 2;
        }

        if (LetvMediaPlayerManager.getInstance().getHardDecodeSupportLevel() == 1) {
            return 1;
        }

        return -1;
    }

    /**
     * 获取加密url
     *
     * @param input
     * @return
     */
    //    public static String getURLFromLinkShell(String input) {
    //        if (BaseApplication.getInstance().getCdeHelper() != null) {
    //            return BaseApplication.getInstance().getCdeHelper().getLinkshellUrl(input);
    //        }
    //
    //        return input;
    //    }
    public static String getURLFromLinkShell(Context context, String input) {
        if (LetvSDKUtils.getCdeHelper(context) != null) {
            return LetvSDKUtils.getCdeHelper(context).getLinkshellUrl(input);
        }

        return input;
    }

    /**
     * 根据播放地址获取PlayUrl
     *
     * @param url
     * @return
     */
    public static PlayUrl getPlayUrl(String url, Type type, int playLevel) {
        PlayUrl playUrl = new PlayUrl();
        playUrl.setVid(101);
        try {
            // 只有是m3u8硬解的时候才需要传playLevel
            if (type == Type.MOBILE_H264_M3U8_HW) {
                playUrl.setStreamType(getPlayLevel2StreamType(playLevel));
            } else {
                playUrl.setStreamType(getPlayLevel2StreamType(-1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        playUrl.setUrl(url);

        return playUrl;
    }

    /**
     * 通过playLevel获取StreamType
     *
     * @param play_level
     * @return
     */
    public static PlayUrl.StreamType getPlayLevel2StreamType(int playLevel) {
        PlayUrl.StreamType streamType = PlayUrl.StreamType.STREAM_TYPE_1000K;
        switch (playLevel) {
            case 1:
                streamType = PlayUrl.StreamType.STREAM_TYPE_180K;
                break;
            case 2:
                streamType = PlayUrl.StreamType.STREAM_TYPE_350K;
                break;
            case 3:
                streamType = PlayUrl.StreamType.STREAM_TYPE_1000K;
                break;
            case 4:
                streamType = PlayUrl.StreamType.STREAM_TYPE_1300K;
                break;
            default:
                streamType = PlayUrl.StreamType.STREAM_TYPE_UNKNOWN;
                break;
        }

        return streamType;
    }

    /**
     * 获取码流名称
     *
     * @return
     */
    //    public static String[] getStreamLevelName() {
    //        String streamName[] = new String[4];
    //        streamName[0] = TipUtils.getTipMessage(DialogMsgConstantId.CONSTANT_100035, R.string.stream_low);
    //        streamName[1] = TipUtils.getTipMessage(DialogMsgConstantId.CONSTANT_100036, R.string.stream_standard);
    //        streamName[2] = TipUtils.getTipMessage(DialogMsgConstantId.CONSTANT_100037, R.string.stream_hd);
    //        streamName[3] = TipUtils.getTipMessage(DialogMsgConstantId.CONSTANT_100038, R.string.stream_superhd);
    //        return streamName;
    //    }
    public static String[] getStreamLevelName(Context context) {
        String streamName[] = new String[4];
        streamName[0] =
                TipUtils.getTipMessage(context, DialogMsgConstantId.CONSTANT_100035, R.string.stream_low);
        streamName[1] =
                TipUtils.getTipMessage(context, DialogMsgConstantId.CONSTANT_100036, R.string.stream_standard);
        streamName[2] =
                TipUtils.getTipMessage(context, DialogMsgConstantId.CONSTANT_100037, R.string.stream_hd);
        streamName[3] =
                TipUtils.getTipMessage(context, DialogMsgConstantId.CONSTANT_100038, R.string.stream_superhd);
        return streamName;
    }

    /**
     * 根据playLevel，得到对应码流名
     *
     * @param hdName
     *         高清
     * @param standardName
     *         流畅
     * @param lowName
     *         极速
     * @param playLevel
     * @return
     */
    public static String getPlayLevelZh(String superName, String hdName, String standardName,
                                        String lowName, int playLevel) {
        if (playLevel == PLAY_LEVEL.HIGH) {
            return hdName;
        } else if (playLevel == PLAY_LEVEL.STANDARD) {
            return standardName;
        } else if (playLevel == PLAY_LEVEL.LOW) {
            return lowName;
        }
        return superName;
    }

}
